package com.dc.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.*;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;

/** 通过聚合数据API或GeoLite2获取ip相关信息
 * @author xingzq
 * @version 1.0
 * @date 2022/2/8 14:31
 */
public class IpUtils {

    public static String getIpMsg(String ip) {
        StringBuffer msg = new StringBuffer();
        Integer flag = 0;//0 聚合api，1 GeoLite2，2 无处理
        try {
            URL url = new URL("http://apis.juhe.cn/ip/ipNewV3?ip=" + ip + "&key=97cc222f646539c046ad6ecf98215034");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String urlString = "";
            String current = null;
            while ((current = in.readLine()) != null) {
                urlString += current;
            }
            System.out.println(urlString);
            JSONObject jsonObject = JSON.parseObject(urlString);
            String resultcode = (String) jsonObject.get("resultcode");
            System.out.println(resultcode);
            JSONObject jo1 = (JSONObject) jsonObject.get("result");
            if (jo1 == null) {
                flag = 1;
                String path = ResourceUtils.getURL("classpath:").getPath() + "static/GeoLite2-City.mmdb";
                File database = new File(path);
                DatabaseReader reader = new DatabaseReader.Builder(database).build(); // 读取数据库内容
                InetAddress ipAddress = InetAddress.getByName(ip);
                CityResponse response = null; // 获取查询结果
                response = reader.city(ipAddress);
                Country country = response.getCountry(); // 获取国家信息
                Subdivision subdivision = response.getMostSpecificSubdivision();  // 获取省份
                City city = response.getCity();     // 获取城市
                msg.append(country.getNames().get("zh-CN")).append(",").
                        append(subdivision.getNames().get("zh-CN")).append(city.getNames().get("zh-CN"));
            } else {
                msg.append(jo1.get("Country")).append(",")
                        .append(jo1.get("Province")).append(jo1.get("City")).append(",")
                        .append(jo1.get("Isp"));
            }
        } catch (IOException | GeoIp2Exception e) {
            e.printStackTrace();
        } finally {
            if (msg.length() == 0) {
                flag = 2;
                msg.append("未知ip");
            }
            msg.append("_").append(flag.toString());
        }
        return msg.toString();
    }


    //demo
    public static void main(String[] args) throws Exception{
        // 创建 GeoLite2 数据库
        File database = new File("../GeoLite2-City.mmdb");
        // 读取数据库内容
        DatabaseReader reader = new DatabaseReader.Builder(database).build();
        InetAddress ipAddress = InetAddress.getByName("183.6.172.114");

        // 获取查询结果
        CityResponse response = reader.city(ipAddress);

        // 获取国家信息
        Country country = response.getCountry();
        System.out.println(country.getIsoCode()); // 'CN'
        System.out.println(country.getName()); // 'China'
        System.out.println(country.getNames().get("zh-CN")); // '中国'

        // 获取省份
        Subdivision subdivision = response.getMostSpecificSubdivision();
        System.out.println(subdivision.getName()); // 'Guangxi Zhuangzu Zizhiqu'
        System.out.println(subdivision.getIsoCode()); // '45'
        System.out.println(subdivision.getNames().get("zh-CN")); // '广西壮族自治区'

        // 获取城市和经纬度
        City city = response.getCity();
        System.out.println(city.getName()); // 'Nanning'
        Postal postal = response.getPostal();
        System.out.println(postal.getCode()); // 'null'
        System.out.println(city.getNames().get("zh-CN")); // '南宁'
        Location location = response.getLocation();
        System.out.println(location.getLatitude()); // 22.8167
        System.out.println(location.getLongitude()); // 108.3167

    }
}
